package org.kl.bf.service.basic;

import java.util.List;
import java.util.Map;

import org.kl.bf.entity.basic.Sessions;
import org.kl.bf.repository.basic.SessionsDao;
import org.kl.bf.utils.CRUDUtils;
import org.kl.bf.utils.KLDynamicSpecifications;
import org.kl.bf.utils.KLSearchFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author hqm
 * @CreateTime 2014年6月17日 下午8:52:08
 */
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional
public class SessionsService {

	private SessionsDao sessionsDao;

	@Autowired
	public void setSessionsDao(SessionsDao sessionsDao) {
		this.sessionsDao = sessionsDao;
	}

	public Sessions getSessions(String guid) {
		return sessionsDao.findOne(guid);
	}

	public void saveSessions(Sessions entity) {
		sessionsDao.save(entity);
	}

	public void deleteSessions(String guid) {
		sessionsDao.delete(guid);
	}

	public List<Sessions> getAllSessions() {
		return sessionsDao.findAll();
	}

	public Page<Sessions> getSessions(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType, String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<Sessions> spec = buildSpecification(searchParams);

		return sessionsDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<Sessions> buildSpecification(Map<String, Object> searchParams) {
		Map<String, KLSearchFilter> filters = KLSearchFilter.parse(searchParams);
		Specification<Sessions> spec = KLDynamicSpecifications.byKLSearchFilter(filters.values(), Sessions.class);
		return spec;
	}

}
